<%@ page import="com.google.appengine.api.blobstore.BlobstoreServiceFactory" %>
<%@ page import="com.google.appengine.api.blobstore.BlobstoreService" %>

<%
    BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
	String websiteCompenentIdentifier = request.getParameter("id");
	
	String uploadUrl = blobstoreService.createUploadUrl("/upload");
	uploadUrl = uploadUrl.substring( uploadUrl.indexOf("8888") + 4, uploadUrl.length());
%>
<html>
<header>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" src="javascript/jquery.form.js"></script>
<script type="text/javascript" src="javascript/jquery.imgareaselect.min.js"></script>
<link 	rel="stylesheet" type="text/css" href="css/imgareaselect-default.css" />
<link rel="stylesheet" href="css/mincko.css">
<script type="text/javascript">
var blobKey = null;
var textDefaultValue = 'Description';
var alreadySubmit = false
var  webComponentIdentifier = "<%= websiteCompenentIdentifier %>"

$(document).ready(function() 
{ 
	//for image upload form.
	$('#photoimg').live('change', function()	{ 
		$("#preview").html('');
		$("#preview").html('<img src="images/loader.gif" alt="Uploading...."/>');
		$("#uploadimage").hide( );
		//$("#dataform").show(1000);
		
 		$("#imageform").ajaxForm(
 		{
 			target: '#preview',
 			dataType: 'json',
 			success: createAreaSelect
 		}).submit();
 	
	});
	
	//for saving image form
	var options = { 
	        target:        '#preview',
	        beforeSubmit:  submitSaveForm, 
	        success:       showResponse  
	    }; 	 
	    $('#descForm').ajaxForm(options)
	    $('#cropButton').hide();
	    
	//to populate the description 
	$("#description").val(textDefaultValue);
	$("#description")
	    .focus(function() {
	          if (this.value === textDefaultValue) {
	              this.value = '';
	          }
	    })
	    .blur(function() {
	          if (this.value === '') {
	              this.value = textDefaultValue;
	          }
	  });
}); 

function createAreaSelect(responseText, statusText, xhr, $form)
{
	
	var status = responseText[1]; // 0=success, 1=Step1, 2=Step2, 3=Step3
	blobKey = responseText[0];
	$('#preview').html("");
	if(status=="3"){ //need cropping
		$('#preview').append("<h2>Please crop your image and save</h2>");
		$('#preview').append("<img  id='imgPreview' src='/serve?blob-key="+ blobKey +"'>");
		var x = responseText[2];
		var y = responseText[3];
		$('#cropButton').show();
        $('input[name="targetWidth"]').val(x);     
        $('input[name="targetHeight"]').val(y);    
        $('input[name="oriWidth"]').val(responseText[4]);     
        $('input[name="oriHeight"]').val(responseText[5]);     
        $('input[name="cropBlobKey"]').val(blobKey);     
        
    	$('#imgPreview').imgAreaSelect({ x1: 0, y1: 0, x2: x, y2: y, resizable: false, onSelectEnd: function (img, selection) {
            $('input[name="x1"]').val(selection.x1);
            $('input[name="y1"]').val(selection.y1);
            $('input[name="x2"]').val(selection.x2);
            $('input[name="y2"]').val(selection.y2);     
        } });
	} // no need to crop
	else{
		$('#preview').html("<img  id='imgPreview' src='/serve?blob-key="+ blobKey +"'>");
		$('#cropButton').hide();
		$("#dataform").show(1000);
	}
}

function submitSaveForm(formData, jqForm, options)
{
	if(!alreadySubmit) alreadySubmit = true
	//cut blobkey from url
	str = $("#preview").html();
	formData[0].value = blobKey //field of blobkey
	if(formData[2].value == textDefaultValue) //if textarea value  = textDefaultValue, dont save
		formData[2].value = "";
	return alreadySubmit;
}

function showResponse(responseText, statusText, xhr, $form){
	alreadySubmit = false;
	if(parent.$('iframe').length != 0){ 
		parent.$('iframe').trigger("refreshList");
		parent.$('#popupContactClose').trigger("click");
	}else //redirect to slideshow_jsp
		window.location.href = "slideshow_list.jsp?id="+webComponentIdentifier
}

function submitCrop(){
	$("#cropImageFrm").ajaxForm(
	 		{
	 			target: '#preview',
	 			dataType: 'json',
	 			success: cropSuccess  
	 		}).submit();
}

function cropSuccess(responseText, statusText, xhr, $form)
{	
	blobKey = responseText[0];
	$('#imgPreview').imgAreaSelect({remove:true});
	$('#cropButton').hide();
	$("#dataform").show(1000);
	$('#preview').html("");
	$('#preview').html("<img  id='imgPreview' src='/serve?blob-key="+ blobKey +"'>");

}
</script>
</header>

<body class='pageUpload'>
<br>
<h1>Upload a new Image to <%= websiteCompenentIdentifier %></h1>
<br>

<div id="dataform" style="display:none;">
<h2>Enter image description and save</h2>
<form id="descForm" method="post" action='saveImage' >
	<input name="blobkey" id="blobkey" type="hidden" value="">
	<input name="websiteComponentIdentifier" type="hidden" value="<%= websiteCompenentIdentifier %>">
	<div class='newLine'><textarea id='description' name ='description' rows="5" cols="30"></textarea></div>
<input type="submit" value="Save">
</form>
</div>

<div id="uploadimage">
<h2>Select the image you want to upload</h2>
<form id="imageform" method="post" enctype="multipart/form-data" action='<%= uploadUrl %>'>
	<input type="file" name="photoimg" id="photoimg" />
</form>
</div>
<button onclick="submitCrop()" id='cropButton'>Save</button>
<div id='preview'>
</div>
<form action="cropImage" method="post" id="cropImageFrm">
  <input type="hidden" name="x1" value="" />
  <input type="hidden" name="y1" value="" />
  <input type="hidden" name="x2" value="" />
  <input type="hidden" name="y2" value="" />
  <input type="hidden" name="targetHeight" value="" />
  <input type="hidden" name="targetWidth" value="" />
  <input type="hidden" name="oriHeight" value="" />
  <input type="hidden" name="oriWidth" value="" />
  <input type="hidden" name="cropBlobKey" value="" />
</form>

</body>
</html>


